package cn.xuqiudong.attachment.web;

/**
 * 描述:
 * @author Vic.xu
 * @since 2022-01-14 9:39
 */

import cn.xuqiudong.attachment.autoconfigure.AttachmentProperties;
import cn.xuqiudong.attachment.util.ClientVerifyUtil;
import cn.xuqiudong.common.base.model.BaseResponse;
import cn.xuqiudong.common.base.tool.Tools;
import cn.xuqiudong.common.base.vo.BooleanWithMsg;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 服务端接口的拦截器 检验客户端合法性
 * @author Vic.xu
 */
public class AttachmentClientCheckInterceptor implements HandlerInterceptor {

    AttachmentProperties attachmentProperties;

    public AttachmentClientCheckInterceptor(AttachmentProperties attachmentProperties) {
        this.attachmentProperties = attachmentProperties;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        String[] conetents = attachmentProperties.getClientSignContents();
        if (conetents == null || conetents.length == 0) {
            return true;
        }
        //sign 可以从header和参数中获取
        String sign = request.getHeader(AttachmentProperties.HEADER_CHECK_NAME);
        if (StringUtils.isBlank(sign)) {
            sign = request.getParameter(AttachmentProperties.HEADER_CHECK_NAME);
        }
        BooleanWithMsg result = ClientVerifyUtil.verifySign(sign, attachmentProperties.getClientSignKey(), conetents);
        if (!result.isSuccess()) {
            Tools.writeJson(BaseResponse.error("不合法的请求:" + result.getMessage()), response);
            return false;
        }
        return true;
    }


}
